﻿@page "/user"

@using BlazorLearnWebApp.Entity

@inject IDataService<UserEntity> _dataService
@inject SwalService _swalService


@attribute [TabItemOption(Text = "用户管理", Icon = "fa-fw fa-solid fa-desktop")]
<AdminTable TItem="UserEntity" OnSaveAsync="OnSaveAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.UserName" IsReadonlyWhenEdit="true"></TableColumn>
        <TableColumn @bind-Field="@context.NickName"></TableColumn>
        <TableColumn @bind-Field="@context.RoleId" Text="角色" LookupServiceKey="role"></TableColumn>
    </TableColumns>
    <RowButtonTemplate Context="value">
        <TableCellPopconfirmButton Text="重置密码" Content=@($"你是否要重置{value.UserName}的密码吗?") OnConfirm="()=>ResetPassword(value)"></TableCellPopconfirmButton>
    </RowButtonTemplate>
</AdminTable>

@code {

    // /// <summary>
    // /// 用户角色
    // /// </summary>
    // private List<SelectedItem>? Roles{ get; set; }

    // protected override async Task OnInitializedAsync()
    // {
    //     await base.OnInitializedAsync();
    //     Roles = RoleEntity.Select.ToList(x => new SelectedItem(x.Id.ToString(), x.RoleName!));
    // }


    private async Task<bool> OnSaveAsync(UserEntity arg1, ItemChangedType arg2)
    {
        if (arg2 == ItemChangedType.Add)
        {
            arg1.Password = arg1.UserName;
        }
        var res = await _dataService.SaveAsync(arg1, arg2);
        if (res && arg2 == ItemChangedType.Add)
        {
            await _swalService.Show(new SwalOption()
                {
                    Category = SwalCategory.Success,
                    Title = "添加用户成功",
                    Content = $"你的密码是{arg1.UserName}"
                });
        }
        return res;
    }

    /// <summary>
    /// 重置密码
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    private async Task ResetPassword(UserEntity user)
    {
        user.Password = user.UserName;
        await user.SaveAsync();
        await _swalService.Show(new SwalOption()
            {
                Category = SwalCategory.Success,
                Title = "重置密码成功",
                Content = $"你的密码是{user.UserName}"
            });
    }
}